from flask import Flask
from config import config_map
from flask_cors import CORS
import logging
from loguru import logger

# 继承原有logging，并重写log日志调用loguru输出方法
class InterceptHandler(logging.Handler):
    def emit(self, record) -> None:
        logger_opt = logger.opt(depth=6, exception=record.exc_info)
        logger_opt.log(record.levelname, record.getMessage())

def create_app(config_name):

    class_name = config_map.get(config_name)
    app = Flask(__name__)
    app.config.from_object(class_name)

    # 自定义logger 日志
    logger.add('logs/simple', rotation='10MB', retention='7 days', encoding='utf-8', enqueue=False)

    # # 将loguru注册为处理程序
    app.logger.addHandler(InterceptHandler())

    # 跨域请求
    CORS(app)

    # 注册蓝图
    from . import api
    app.register_blueprint(api.api, url_prefix="/api/v1.0")
    return app